package light.mvc.controller.books;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.base.Tree;
import light.mvc.pageModel.books.BooksModel;
import light.mvc.pageModel.books.Material;
import light.mvc.pageModel.books.MyFileUpload;
import light.mvc.service.books.BooksServiceI;
import light.mvc.service.books.VideoServiceI;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("ebook")
public class BooksController {

	@Autowired
	private BooksServiceI booksService;
	@Autowired
	private VideoServiceI videoService;

	@RequestMapping({ "/lib" })
	public String manager() {
		return "/books/books";
	}

	@RequestMapping({ "/video" })
	public String video() {
		return "/books/video";
	}

	@RequestMapping({ "/ppt" })
	public String ppt() {
		return "/books/video_fileupload_progress_bar";
	}

	@RequestMapping({ "/uploaddialog" })
	public String uploaddialog() {
		return "/books/books_fileupload";
	}

	@RequestMapping({ "/uploadVideo" })
	public String uploadVideo(@ModelAttribute MyFileUpload myFileUpload) throws UnsupportedEncodingException {
		myFileUpload.setMyFilePath(URLDecoder.decode(myFileUpload.getMyFilePath(), "utf-8"));
		myFileUpload.setMyId(URLDecoder.decode(myFileUpload.getMyId(), "utf-8"));
		return "/books/video_fileupload";
	}

	@RequestMapping({ "/newFolderUI" })
	public String newFolderUI(@ModelAttribute MyFileUpload myFileUpload) throws UnsupportedEncodingException {
		myFileUpload.setMyFilePath(URLDecoder.decode(myFileUpload.getMyFilePath(), "utf-8"));
		myFileUpload.setMyId(URLDecoder.decode(myFileUpload.getMyId(), "utf-8"));
		return "/books/video_newFolder";
	}

	@RequestMapping({ "/newFolder" })
	@ResponseBody
	public Json newFolder(String filePath, Material material) {
		Material m = material;
		String path = filePath + "/" + m.getName();
		m.setUrl(path);
		m.setMaterialType(0);
		Json j = new Json();
		File dir = new File(path);
		boolean mkresult = false;
		;
		if (!dir.exists()) {
			mkresult = dir.mkdirs();
		}
		if (!mkresult) {
			j.setSuccess(false);
			return j;
		}
		try {
			m.setState("closed");
			videoService.add(m);
			j.setSuccess(true);
			j.setMsg("添加成功！");
		} catch (Exception e) {
			j.setMsg(e.getMessage());
			e.printStackTrace();
		}
		return j;
	}

	@RequestMapping({ "/dataGrid" })
	@ResponseBody
	public Grid dataGrid(BooksModel books, PageFilter ph) {
		Grid grid = new Grid();
		grid.setRows(this.booksService.dataGrid(books, ph));
		grid.setTotal(this.booksService.count(books, ph));
		return grid;
	}

	// 处理文件上传一
	@RequestMapping(value = "fileUpload2", method = RequestMethod.POST)
	@ResponseBody
	public Json fileUpload(@RequestParam("fileUpload") CommonsMultipartFile file,//
			String filePath, String parentId,//
			@RequestParam("loginUserId") String loginUserId,//
			@RequestParam("description") String description//
			) {
		if (!file.isEmpty()) {
			String path = filePath + "/" + file.getOriginalFilename();
			BooksModel booksModel = new BooksModel();
			Material material = new Material();
			material.setUrl(path);
			material.setParentId(Long.valueOf(parentId));
			material.setName(file.getOriginalFilename());
			material.setMaterialType(1);
			material.setSize(Long.valueOf(file.getSize() / 1024).intValue());
			material.setBuilderId(Long.valueOf(loginUserId));
			material.setDescription(description);
			booksModel.setName(file.getOriginalFilename());

			booksModel.setSize(file.getSize() / 1024);
			this.booksService.add(booksModel);
			this.videoService.add(material);
			File localFile = new File(path);
			try {
				file.transferTo(localFile);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Json j = new Json();
		try {
			j.setSuccess(true);
			j.setMsg("添加成功！");
		} catch (Exception e) {
			j.setMsg(e.getMessage());
		}
		return j;
	}

	@RequestMapping(value = "/AppUpload.action", method = RequestMethod.POST)
	public ModelAndView Upload(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		try {
			String path = request.getSession().getServletContext().getRealPath("/");
			path = path.substring(0, path.length() - 1);
			int p = path.lastIndexOf("\\");
			path = path.substring(0, p);
			path = path.replace("\\", "/");

			String folderPath = path + "/ftp/upload/";

			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("filedata");
			// filedata 是表单的名字

			InputStream stream = file.getInputStream();
			String fileName = file.getOriginalFilename();
			String fileNameFull = folderPath + fileName;
			File filea = new File(folderPath);
			if (!filea.exists()) {
				filea.mkdirs();
			}
			OutputStream bos = new FileOutputStream(fileNameFull);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}

			bos.close();
			stream.close();
			modelMap.put("msg", "添加成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("/appupload", modelMap);
	}

	@RequestMapping(value = "download", method = RequestMethod.GET)
	public static void download(HttpServletRequest request, HttpServletResponse response, String fileName, String path) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		String newFileName = new String(fileName.getBytes("ISO8859-1"), "UTF-8");
		String ctxPath = new String(path.getBytes("ISO8859-1"), "UTF-8");
		;
		String downLoadPath = ctxPath;
		long fileLength = new File(downLoadPath).length();
		response.setHeader("Content-disposition", "attachment; filename=" + newFileName);
		response.setHeader("Content-Length", String.valueOf(fileLength));
		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}

	@RequestMapping(value = "download2", method = RequestMethod.GET)
	public static ModelAndView download2(MyFile file) {
		System.out.println(file.getFileName());
		System.out.println(file.getFileSize());
		ModelAndView mav = new ModelAndView();
		mav.setViewName("meetingroom/createSuccess");
		mav.addObject("file", file);
		return mav;
	}

	/*
	 * 下面是用于测试
	 */
	@RequestMapping("/tree")
	@ResponseBody
	public List<Tree> tree(HttpSession session,@RequestParam(value="id" ,required=false) String id) {
		return videoService.allTree(true,id);
	}

	@RequestMapping("/delete")
	@ResponseBody
	public Json delete(Long id) {
		Json j = new Json();
		try {
			videoService.delete(id);
			j.setMsg("删除成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("删除不成功,该文件夹不为空!");
		}
		return j;
	}

/*	@RequestMapping("/edit")
	@ResponseBody
	public Json edit(Dictionarytype dictionarytype) {
		Json j = new Json();
		try {
			videoService.edit(dictionarytype);
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			j.setMsg(e.getMessage());
		}
		return j;
	}*/

	@RequestMapping({ "/dataGridForMaterial" })
	@ResponseBody
	public Grid dataGridForMaterial(Material material, PageFilter ph) {
		Grid grid = new Grid();
		grid.setRows(this.booksService.dataGrid(material, ph));
		grid.setTotal(this.booksService.count(material, ph));
		return grid;
	}

}